require(['select2', 'validator', 'ajaxfileupload'], function () {
    var editDialog,
        $formData = $('#formData'),
        baseBlackArchivesInfo = "";

    $formData.initForm();

    //危险程度
    var $dangerous = $('.dangerous-setting');
    $dangerous.on('click', 'span', function () {
        $(this).addClass('active').prevAll().addClass('active');
        $(this).nextAll().removeClass('active');
    });

    window.add = function (fn) {
        addOrUpdate("/baseBlackArchivesInfo/addBaseBlackArchivesInfo.htm", fn);
    };

    window.edit = function (fn) {
        addOrUpdate("/baseBlackArchivesInfo/uptBaseBlackArchivesInfo.htm", fn);
    };

    window.setFormValues = function (rcrdId) {
        //清空值
        cleanValues();

        $.ajaxExt({
            url: "/baseBlackArchivesInfo/getBaseBlackArchivesInfoById.htm",
            data: {'rcrdId': rcrdId}
        }).done(function (data) {
            if (data) {
                baseBlackArchivesInfo = data;
                setValues(data);
            } else {
                $.messager.alert("警告", "没有相关数据！", "info");
            }
        });
    };

    //清空
    window.clean = function () {
        baseBlackArchivesInfo = "";// 将页面的值清空

        cleanValues();
    };

    //重置
    window.reset = function () {
        if (baseBlackArchivesInfo) {
            setValues(baseBlackArchivesInfo);
        } else {
            cleanValues();
        }
    };

    /**
     * 新增保存或者修改保存
     * @param url
     * @param callBack
     */
    function addOrUpdate(url, callBack) {
        var result = $.validator($formData);
        if (result) {
            $.ajaxExt({
                url: url,
                data: getValues()
            }).done(function (data) {
                baseBlackArchivesInfo = "";
                callBack();
            });
        }
    }

    //设置值：将数据进行展示
    var setValues = function (data) {
        //表单设置值
        $formData.setValues(data);

        //危险度设置展示
        if (data.dangerDegree) {
            var dangerDegree = data.dangerDegree;

            var $active = $('.dangerous-setting span').eq(dangerDegree - 1);
            $active.addClass('active').prevAll().addClass('active');
            $active.nextAll().removeClass('active');
        }

        //清空myfiles的值
        $("input[name='myfiles']").val('');
        
        //图片展示清空
        $('.upload-wrap img').attr({'src': ''});

        //图片设置展示
        if (data.blackPic1) {
            viewPicFile('blackPic1Url', 'blackPic1', data.blackPic1);
        }
        if (data.blackPic2) {
            viewPicFile('blackPic2Url', 'blackPic2', data.blackPic2);
        }
        if (data.blackPic3) {
            viewPicFile('blackPic3Url', 'blackPic3', data.blackPic3);
        }
        if (data.blackPic4) {
            viewPicFile('blackPic4Url', 'blackPic4', data.blackPic4);
        }

        //是否已经设置地图区域
        if (data.fencId) {
            $('#mapArea').val('已设置地图区域');
        } else {
            $('#mapArea').val('请选择地图区域');
        }
    };

    //得到值：封装数据
    var getValues = function () {
        //得到经纬度的值
        var loLgtloLtt = $('#loLgtloLtt').val();

        if (loLgtloLtt && loLgtloLtt.indexOf(',') != -1) {
            var data = loLgtloLtt.split(",");
            $('#loLgt').val(data[0]);
            $('#loLtt').val(data[1]);
        }

        //得到危险度的值
        var dangerDegree = $('.dangerous-setting .active').size();
        $('#dangerDegree').val(dangerDegree);

        //得到表单的值
        var formData = $formData.getValues()

        return formData;
    }

    //清空值：将界面设置为默认状态
    var cleanValues = function () {
        //表单值清空
        $formData.reset();

        //危险度展示清空
        $('.dangerous-setting span').removeClass('active');

        //图片展示清空
        $('.upload-wrap img').attr({'src': ''});

        //恢复默认
        $('#mapArea').val('请选择地图区域');
    }

    //图片上传
    window.upload = function (el) {
        if ($(el).val()) {
            var parent = el.parentNode;
            uploadCardFrontPicFile(el.id, $('img', parent).attr('id'), $('input[type="hidden"]', parent).attr('id'));
        }
    };

    function viewPicFile(imgId, urlInputId, url) {
        $('#' + imgId).attr("src", $.getProjectName() + "/baseBlackArchivesInfo/readImage.htm?uploadPath=" + url);
        $('#' + urlInputId).val(url);
    }

    //上传图片方法
    function uploadCardFrontPicFile(fileElementId, imgId, urlInputId) {
        $.ajaxFileUpload({
            url: $.getProjectName() + "/baseBlackArchivesInfo/uploadImage.htm",//需要链接到服务器地址
            secureuri: false,
            fileElementId: fileElementId,//文件选择框的id属性
            data: {//加入的文本参数
                "uploadPath": "/files/upload/" + (new Date()).format() + "/"
            },
            dataType: 'text',   //json
            success: function (data, status) {
                data = data.replace(/<\/*?pre[^<>]*>/, '');  //ajaxFileUpload会对服务器响应回来的text内容加上<pre>text</pre>前后缀
                //本例中设定上传文件完毕后,服务端会返回给前台[0`filepath]
                if (data.substring(0, 1) == 0) {
                    $('#' + imgId).attr("src", $.getProjectName() + "/baseBlackArchivesInfo/readImage.htm?uploadPath=" + data.substring(2));
                    $('#' + urlInputId).val(data.substring(2));
                } else {
                    //alert("上传图片失败！" + data.substring(2));
                    $.messager.alert("错误", "上传图片失败", "error");
                }
            },
            error: function (data, status, e) {
                //alert(data.responseText);
                $.messager.alert("错误", "上传图片失败", "error");
            }
        });
    }

    //上传黑点图片
    $('.img-upload img').on('click', function () {
        $(':file', this.parentNode).trigger('click');
    });

    //删除上传的黑点图片
    $('.close-btn2').on('click', function (e) {
        $('input', this.parentNode).val("");
        $('img', this.parentNode).attr("src", "");
    });

    //选择黑点地图区域
    $('#mapArea').on('click', function () {
        if ($('#fencId').val()) {
            getEditDialog({title: '修改地图区域'}).dialog('exec', 'getElectFence', $('#fencId').val());
        } else {
            getEditDialog({title: '选择地图区域'});
        }
    });

    var $locationChooseWin;
    $('.icon-location').on('click', function () {
        if (!$locationChooseWin) {
            $locationChooseWin = $('<div>').dialog({
                title: '经纬度选择',
                url: './common/map/locationChoose.htm',
                height: $(window.parent).height() * 0.85,
                width: $(window.parent).width() * 0.85,
                buttons: [
                    {
                        text: '确定',
                        css: 'mr10',
                        click: function () {
                            $('#loLgtloLtt').val($(this).dialog('exec', 'getLgtLtt'));
                            $(this).dialog('close');
                        }
                    }
                ]
            })
        }
        $locationChooseWin.dialog('open');
        $locationChooseWin.dialog('exec', 'setLgtLtt', $('#loLgtloLtt').val());
    });

    /**
     * 获取表单对话框，如果没有就先创建
     * @param option {object} 对话框配置
     * @returns {jQuery}
     */
    function getEditDialog(option) {
        option = option || {};
        if (editDialog) {
            if (option.title) {
                editDialog.dialog('setOption', 'title', option.title);
            }

            editDialog.dialog('open');
            editDialog.dialog('exec', 'clearAll');
        } else {
            editDialog = $('<div>').dialog({
                title: option.title || '电子围栏设置',
                url: './safety/setting/funBlackspotEnclMap.htm',
                height: $(window.parent).height() * 0.8,
                width: $(window.parent).width() * 0.8,
                autoOpen: true,
                buttons: [
                    {
                        text: '确定',
                        css: 'mr10',
                        click: function () {
                            var _t = this;
                            $(_t).dialog('exec', "saveOrUpdate", function (data) {
                                $(_t).dialog('close');
                                //@xujf@todo(回显)
                                if (data) {
                                    $('#mapArea').val('已设置地图区域');
                                    $('#fencId').val(data.fencId)
                                }
                            });
                        }
                    },
                    {
                        text: '重置',
                        css: 'btn-cancel',
                        click: function () {
                            $(this).dialog('exec', 'reset');
                        }
                    }
                ]
            });
        }
        return editDialog;
    }

});